// 该方法当前页不是第一视图时（包含子路由已显示）务必移除，否则有未知错误
let callbacks;
let hasListenersBack = false;
let listenersBackIdentifier;

function popstateFun() {
  callbacks();
  window.removeEventListener("popstate", popstateFun);
  hasListenersBack = false;
  listenersBackIdentifier = null;
}
class PopstateHandler {
  // 页面中有多处需要注册时加上identifier区分
  popstateListener(callback, identifier) {
    if (!hasListenersBack) {
      hasListenersBack = true;
      callbacks = callback;
      listenersBackIdentifier = identifier;
      history.pushState(null, "", location.href);
      window.addEventListener("popstate", popstateFun);
    }
  }
  removePopstateListener(identifier) {
    // 监听时未添加标识或者与监听时添加标识一样可移除
    setTimeout(() => {
      if ((listenersBackIdentifier && listenersBackIdentifier === identifier) || !identifier) {
        window.removeEventListener("popstate", popstateFun);
        hasListenersBack = false;
        listenersBackIdentifier = null;
        history.back()
      }
    });
  }
}
export const popstateHandler = new PopstateHandler();